package me.jiatao.wan.ui.main.home

import android.os.Bundle
import android.view.View
import android.widget.Toast
import androidx.core.view.isVisible
import androidx.fragment.app.Fragment
import androidx.fragment.app.viewModels
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import androidx.paging.LoadState
import com.google.android.material.appbar.AppBarLayout
import com.hi.dhl.binding.viewbind
import com.youth.banner.indicator.CircleIndicator
import dagger.hilt.android.AndroidEntryPoint
import kotlinx.coroutines.delay
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.flow.distinctUntilChangedBy
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.launch
import me.jiatao.wan.R
import me.jiatao.wan.common.ui.LoadingLottieAnimation
import me.jiatao.wan.data.network.doFailure
import me.jiatao.wan.data.network.doSuccess
import me.jiatao.wan.databinding.FragmentHomeBinding
import me.jiatao.wan.paging3.footer.FooterAdapter
import me.jiatao.wan.paging3.home.HomeArticleAdapter
import timber.log.Timber

@AndroidEntryPoint
class HomeFragment : Fragment(R.layout.fragment_home), AppBarLayout.OnOffsetChangedListener {

    private val mBinding: FragmentHomeBinding by viewbind()
    private val mainViewModel by viewModels<HomeViewModel>()
    private val articlePagingAdapter by lazy { HomeArticleAdapter() }

    /**
     * 设置动画加载状态
     */
    private val loadingState = MutableLiveData<LoadingLottieAnimation.State>()

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        mBinding.apply {
            //recyclerView.itemAnimator = null
            recyclerView.adapter =
                articlePagingAdapter.withLoadStateFooter(FooterAdapter(articlePagingAdapter))

            /** 监听appbar滑动 */
            appBar.addOnOffsetChangedListener(this@HomeFragment)

            /** 处理浮标点击事件 */
            fab.setOnClickListener {
                /** 当前为向上按钮 */
                if (it.tag == null) {
                    recyclerView.scrollToPosition(0)
                    appBar.setExpanded(true)
                } else {
                    /** 当前为搜索按钮 */
                    Toast.makeText(requireActivity(), "查询", Toast.LENGTH_LONG).show();
                }

                
//                println("11111111")
//                articlePagingAdapter.snapshot()[0]?.let {
//                    it.author = "xxx"
//                    articlePagingAdapter.notifyItemChanged(0)
//                }
            }
            /** 下拉刷新 */
            swiperRefresh.setOnRefreshListener {
                articlePagingAdapter.refresh()
                handBanner()
            }

            loadingLayout.retryButton.setOnClickListener {
                articlePagingAdapter.refresh()
                handBanner()
            }

            /** 监听加载状态 */
            loadingState.observe(viewLifecycleOwner) { state ->
                if (layoutHeader.homeBanner.adapter == null) {
                    loadingLayout.lottieAnimation.status = state
                    loadingLayout.retryButton.isVisible = state == LoadingLottieAnimation.State.ERROR
                }
               else{
                    loadingLayout.lottieAnimation.status = LoadingLottieAnimation.State.COMPLETE
                    loadingLayout.retryButton.isVisible = false
               }
            }
        }

        /** 根据加载状态显示刷新状态 */
        lifecycleScope.launchWhenCreated {
            articlePagingAdapter.loadStateFlow
                .distinctUntilChangedBy { it.refresh }
                .collectLatest { states ->
                    mBinding.swiperRefresh.isRefreshing = states.refresh is LoadState.Loading
                    when (states.refresh) {
                        is LoadState.NotLoading -> {
                            println("refresh ---> NotLoading")
                        }
                        is LoadState.Loading -> {
                            println("refresh ---> Loading")
                        }
                        is LoadState.Error -> {
                            println("refresh ---> Error: " + Thread.currentThread().name)
                            Toast.makeText(
                                requireContext(),
                                (states.refresh as LoadState.Error).error.message,
                                Toast.LENGTH_SHORT
                            ).show()
                        }
                    }
                }
        }

        /**
         * 加载文章列表
         */
        mainViewModel.loadHomeArticleListVM().observe(viewLifecycleOwner) {
            articlePagingAdapter.submitData(lifecycle, it)
            mBinding.swiperRefresh.isRefreshing = false
        }

        handBanner()
    }

    /**
     * 加载轮播图
     */
    private fun handBanner() {
        lifecycleScope.launch {

            mainViewModel.fetchBannerFlow
                .onStart {
                    loadingState.value = LoadingLottieAnimation.State.LOADING
                }
                .collectLatest { result ->
                    result.doFailure { apiException ->
                        loadingState.value = LoadingLottieAnimation.State.ERROR
                        apiException.message?.let {
                            Timber.e(it)
                        }
                    }
                    result.doSuccess { listBanner ->
                        loadingState.value = LoadingLottieAnimation.State.COMPLETE
                        mBinding.layoutHeader.homeBanner
                            .setAdapter(HomeBannerAdapter(listBanner))
                            .addBannerLifecycleObserver(requireActivity())
                            .setIndicator(CircleIndicator(requireActivity()))
                    }
                }
        }
    }


    /**
     * 监听AppBar滑动解决swiperRefresh冲突问题
     */
    override fun onOffsetChanged(appBarLayout: AppBarLayout?, verticalOffset: Int) {
        if (verticalOffset >= 0) {
            /** 查询状态*/
            if (mBinding.fab.tag == null) {
                mBinding.apply {
                    //开启加载框
                    swiperRefresh.isRefreshing = false
                    swiperRefresh.isEnabled = true
                    //开启轮播图
                    layoutHeader.homeBanner.start()
                    //使用查询按钮
                    fab.setImageResource(R.drawable.ic_search)

                    fab.tag = true
                }
            }

        } else {
            /** 向上状态 */
            if (mBinding.fab.tag != null) {
                mBinding.apply {
                    //关闭加载框
                    swiperRefresh.isRefreshing = false
                    swiperRefresh.isEnabled = false
                    //关闭轮播图
                    layoutHeader.homeBanner.stop()
                    //使用置顶按钮
                    fab.setImageResource(R.drawable.ic_goto_top)
                    fab.tag = null
                }
            }
        }
    }

}